﻿using System;
using System.Windows.Documents;
using RG.Common.WPF.Reporting;
using Microsoft.Practices.Unity;
using RG.Common;
using RG.Common.WPF;

namespace RG.Common.WPF.Frames
{
    public interface IReportFrameVM
    {
        WorkplaceWorker Worker { get; }
        FixedDocumentSequence ReportDoc { get; }
    }

    public interface IReport
    {
        XpsReport report { get; }
    }

    public interface IReportView<T> : IReport
    {
        T Presenter { get; set; }
    }

    public class ReportFrameImpl<T> : ReportFrame, IView<T> where T: IReportFrameVM
    {
        T IView<T>.Presenter
        {
            get { return (T)Presenter; }
            set { Presenter = value; }
        }
    }

    public static class UnityContainerCreateViewExtension
    {
        public static IReport CreateReport(this IUnityContainer container, object presenterVM)
        {
            //для варианта если в конструкторе отчета лежит typeof(presenterVM)
            if (presenterVM is Type)
            {
                #region obj = container.Resolve<IReportView<presenterVM>>

                var viewGenericType = typeof(IReportView<>);

                var ttt = container.Resolve(presenterVM as Type);
                var viewType = viewGenericType.MakeGenericType(new[] {ttt.GetType()});
                var obj = container.Resolve(viewType);

                #endregion

                #region obj.Presenter = presenterVM

                var methodInfo = viewType.GetMethod("set_Presenter");
                methodInfo.Invoke(obj, new[] {ttt});

                #endregion

                return (IReport)obj;
            }
            //для варианта если в конструкторе отчета лежит Cfg.Resolve<presenterVM>()
            else
            {
                #region obj = container.Resolve<IReportView<presenterVM>>

                var viewGenericType = typeof(IReportView<>);

                var viewType = viewGenericType.MakeGenericType(new[] {presenterVM.GetType()});
                var obj = container.Resolve(viewType);

                #endregion

                #region obj.Presenter = presenterVM

                var methodInfo = viewType.GetMethod("set_Presenter");
                methodInfo.Invoke(obj, new[] {presenterVM});

                #endregion

                return (IReport)obj;
            
            }
        }
    }
}